$(function(){
    $.fn.reset = function(){
        $(this).each(function(){
            this.reset();
        });
    }
    $.fn.disabled = function(disabled){
        if(disabled) $(this).attr("disabled", "-1");
        else $(this).removeAttr("disabled");
    }
    $.fn.loader = function(visible){
        var s = $(this);
        
        if(!visible){
            $('#IDLoadCropIcon').fadeIn("medium", function(){
                $(this).remove();
            });
            $('#IDLoadCrop').fadeIn("medium", function(){
                $(this).remove();
            });
            return;
        }
        
        s.prepend('<div id="IDLoadCrop"></div>');
        s.prepend('<div id="IDLoadCropIcon"><img src="./Resouces/images/loader-icon.gif" align="absmiddle" width="16" height="16" /><span>Chargement..</span></div>');
		
        var idText = $('#IDLoadCropIcon');
        var idLoad = $('#IDLoadCrop');
		
        idLoad.css({
            width: s.width()+'px',
            height: s.height()+'px',
            opacity: (40/100)
        });
        
        idText.css({
            marginLeft: (s.width() / 2) - (idText.width() / 2) + "px",
            marginTop: (s.height() / 2) - (idText.height() / 2) + "px"
        });
		
        idLoad.focus().select();
    }
	
    var modes = {
        None: 0, 
        Insert: 1, 
        Update: 3, 
        Delete: 2
    }
	
    $.extend({
        isAtach: false,
        isMode: modes.None,
        id: 0,
        heightMin: 55,
        image: null,
        isLoader: false,
        formValidator: null,
        formLogos: $("#frmLogos"),
        popup: $("#JLModalLogos"),
        UIEditLogos: $("#IDLogosNew"),
        UILogos: $("#IDLogos"),
        UICrop: $("#JLModalCrop"),
        uploader: $("#fileUpload"),
        grid: $("#jqGrid"),
        sortable: $("#IDSortable"),
        editor: null,
        init: function(){
            var s = this;
            s.addBindEvents();
            s.initDragBoxes();
            s.initGrid();
            s.UIEditLogos.hide();
            s.setValidator();
            s.makeUploader( '/csme.fr/images/annonces', '15091456', false, false);
        //            s.UICrop.hide();
        },
        addBindEvents: function(){
            var s = this;
	
            s.popup.xpopup({
                close: true,
                closeTitle: 'Fermer la fenêtre',
                closeEsc: true,
                opacity: 70,
                overlayClose: true,
                width: 'auto'
            });
            
            s.UICrop.xpopup({
                close: true,
                closeTitle: 'Fermer la fenêtre',
                closeEsc: true,
                opacity: 70,
                overlayClose: true,
                width: 'auto'
            });
        
            // LOGOS
            $("#idHide").bind("click", function(e){
                s.sortLogos();
                s.popup.xpopup('hide');
            });
            
            $("#sUIInsert").bind("click", function(e){
                s.id = 0;
                s.isMode = modes.Insert;
                $('#lbl-okfile').hide();
                s.isAtach = false;
                s.newUILogos();
                s.makePopup();
            });
            
            $("#sUIUpdate").bind("click", function(e){
                s.isMode = modes.Update;
                s.id = 0;
                var id = s.grid.jqGrid('getGridParam','selrow');
                
                if(id){
                    var row = s.grid.jqGrid('getRowData', id);
                    s.id = row.int_id_logo;
                    s.editUILogos(s.id);
                } else { 
                    alert("Avertissement\nVeuillez s\u00E9lectionner le logo \u00E0 modifier.");
                }
            });
            
            $("#sUIDelete").bind("click", function(e){
                s.isMode = modes.Update;
                s.id = 0;
                var id = s.grid.jqGrid('getGridParam','selarrrow');
				
                if(id != ""){
                    /*var row = s.grid.jqGrid('getRowData', id);
					s.id = row.int_id_logo;*/
                    s.removeLogo(id);
                }else 
                    alert("Avertissement\nVeuillez s\u00E9lectionner le(s)logo(s) \u00E0 effacer.");
            });
			
            $("#btn-cancel").bind("click", function(e){
                s.isAtach = false;
                if(s.image) s.image.data = null;
                s.visibilityUILogos(false);
                s.popup.xpopup('hide');

            });

            $("#idAnnuler").bind("click", function(e){
                s.removeCrop();
            });
            
            s.formLogos.bind("submit", function(e){
                if(s.isMode == modes.Insert){
                    s.saveInsertLogo();
                }
                if(s.isMode == modes.Update){
                    s.saveUpdateLogo();
                }

                return false;
            });
            
            $("#idCouper").bind("click", function(e){
                if(!s.isLoader){
                    if(s.isSelectedCrop()){
                        s.visibleLoader(true);
                        s.setCropImage();
                    }
                    else{
                        alert("S\u00E9lectionner la zone de recadrage.");
                    }
                }
            });
        },
		
        // LOGOS
        makePopup: function(){
            var s = this;
            s.popup.xpopup('show');
        },
        initDragBoxes: function(){
            var s = this;
            $(".column").sortable({
                stop: function(event, ui){
                    s.sortLogos();
                }
            });
			
            $(".column").disableSelection();
        },
        sortLogos: function(){
            var s = this;
            var i = 1;
            var k = 0;
            var t = s.sortable.find("li").length;
            var data = "[";
			
            s.sortable.find("li").each(function(){
                data += "{\"id\": " + $(this).attr('code') + ", \"order\": " + i + "}, ";
                i++;			
            });
			
            data += "{\"id\": 0, \"order\": 0}]";
			
            if(i>1) $.post("./?ws=Logos&act=sortLogos", {
                data: data, 
                time:new Date().getTime()
            });
        },
        initGrid: function(){
            var s = this;
            s.grid.jqGrid({
                // <MODIFICAR>
                url: './Queries/query-annonces.php?nd=' + new Date().getTime(),
                colNames:['int_id_logo', 'Logo', 'Titre', 'Publi&eacute;', 'Taille', 'Etat'],
                colModel:[{
                    hidden:true, 
                    search:false, 
                    name:'int_id_logo', 
                    index:'int_id_logo',
                    align:'left'
                },{
                    name:'var_src', 
                    index:'var_src', 
                    align:'left', 
                    sortable:false, 
                    formatter:s.formatImage
                },{
                    name:'var_title', 
                    index:'var_src', 
                    align:'left'
                },{
                    name:'dat_creation', 
                    index:'dat_creation', 
                    align:'left'
                },{
                    name:'var_size', 
                    index:'var_size', 
                    align:'center'
                },{
                    name:'var_htmldesc', 
                    index:'var_htmldesc', 
                    align:'left'
                }],
                sortname: ['int_id_logo'],
                sortorder: "desc",
                width: 938,
                height: 300,
                rownumbers: true,
                autowidth: true,
                // </MODIFICAR>	
                loadtext: 'Chargement...',
                datatype: "json",
                pager: '#jqpager',
                rowNum: 20,
                rowList:[10, 20, 50],	
                viewrecords: true,
                multiselect: true
            })
        },
        formatImage: function(cellvalue, options, rowObject){
            return cellvalue !='0' ? "<img src=\"../images/annonces/thumbs/" + cellvalue + "?nd=" + new Date().getTime() + "\" height=\"24\" />" : '';
        },
        formatPlanche:  function(cellvalue, options, rowObject){
            return "<b> Planche " + cellvalue + "</b>";
        },
        makeUploader: function(_folder, _sizeLimit, _multi, photos){
            var s = this;
            s.uploader.uploadify({
                uploader   : './Resouces/js/uploader_new/uploadify.swf',
                script     : './Resouces/js/uploader_new/uploadify.php',
                cancelImg  : './Resouces/js/uploader_new/cancel.png',
                folder     : _folder,
                /*scriptData : {mywork: $.idd},
				queueID    : 'IDFile',*/
                buttonText : 'Parcourir',
                fileDesc   : 'Format de l\'image *.jpg uniquement.',
                fileExt	   : '*.jpg',
                sizeLimit  : _sizeLimit,
                auto       : true,
                multi      : _multi,
                onSelectOnce: function(event, data){
                    $("#btn-save").attr("disabled", "-1");
                    $("#btn-cancel").attr("disabled", "-1");
                    $('#lbl-okfile').hide();
                },
                onCancel: function(event, queueID, file, data){
                    s.iconError(true, "S&eacute;lectionnez une image");
                    s.isAtach = false;
                    $("#btn-save").removeAttr("disabled");
                    $("#btn-cancel").removeAttr("disabled");
                },
                onComplete: function(event, queueID, fileObj, response, data){
                    $("#btn-save").removeAttr("disabled");
                    $("#btn-cancel").removeAttr("disabled");
                    s.image = {
                        name: fileObj.name, 
                        path: "../images/annonces/" + fileObj.name, 
                        obj: null,
                        tSize: null,
                        size: null,
                        data: null
                    };
                },
                onAllComplete: function(event, data){
                    s.loadImage(s.image.path);
                },
                onError: function(event, queueSizeLimit){
                    s.iconError(true, "S&eacute;lectionnez une image");
                    s.isAtach = false;
                    $("#btn-save").removeAttr("disabled");
                    $("#btn-cancel").removeAttr("disabled");
                }
            });
        },
        loadImage: function(path){
            var s = this;
            s.visibleLoader(true);
			
            $(new Image()).load(function(){
                var img = this;
                
                $(img).attr({
                    'width': img.width,
                    'height': img.height
                }).css({
                    'width': img.width,
                    'height': img.height
                });
                
                s.visibilityUILogosCrop(true);
                
                $('#IDPhoto').append(img);
                s.makeCrop(img);


                setTimeout(function(){
                    s.UICrop.xpopup('resize');
                }, 10);

            }).error(function(){ 
                alert("Erreur de chargement de l'image.");
            }).attr('src', s.image.path + '?rnd' + new Date().getTime());
        },
        visibleLoader: function(visible){
            var s = this;
			
            if(!visible){
                $('#IDLoadCropIcon').remove();
                $('#IDLoadCrop').remove();
                s.isLoader = false;
                return;
            }

            var cont = $("#IDContent");
			
            cont.prepend('<div id="IDLoadCrop"></div>');
            cont.prepend('<div id="IDLoadCropIcon"><img src="./Resouces/images/loader-icon.gif" align="absmiddle" width="16" height="16" /><span>Chargement..</span></div>');
			
            var idText = $('#IDLoadCropIcon');
            var idLoad = $('#IDLoadCrop');
			
            idLoad.css({
                width: cont.width() + 'px',
                height: cont.height() + 'px',
                opacity: (60/100)
            });
            idText.css({
                marginLeft: (cont.width() / 2) - (idText.width() / 2) + "px",
                marginTop: (cont.height() / 2) - (idText.height() / 2) + "px"
            });
            s.isLoader = true;
            cont.focus().select();
        },
        iconError: function(_bool, _title){
            $('#lbl-okfile').css('display','none');
            var _icon = "";
            if(_bool) _icon = './Resouces/images/cancelfield.png';
            else _icon = './Resouces/images/okfield.png';
			
            $('#lbl-okfile').html('<img src="'+_icon+'" alt="'+_title+'" title="'+_title+'" />');
            $('#lbl-okfile').fadeIn();
        },
        setValidator: function(){
            var s = this;
            s.formValidator = s.formLogos.validate({
                event: "blur",
                rules:{ 
                    'txttitre': "required",
                    'cboetat': "required"
                },
                messages:{
                    'txttitre': "Entrez votre titre.",
                    'cboetat': "S&eacute;lectionnez l'&eacute;tat."
                }
            });
            
            new nicEditor({
                buttonList: [
                'bold','italic','underline','strikethrough','left','justify','link','unlink','removeformat'
                ],
                iconsPath: './Resouces/js/wysiwyg/nicEditorIcons.gif',
                maxHeight: 180
            }).panelInstance('txtdescription',{
                hasPanel : true
            });

            s.editor = nicEditors.findEditor('txtdescription');
        },
        selectCombo: function(combo, value){
            combo.find("option").each(function(){
                if($(this).val() == value){
                    $(this).attr('selected', 'selected'); 
                }
            });
        },
        newUILogos: function(){
            var s = this;
            s.editor.setContent('');

            s.visibilityUILogos(true, true);
        },
        editUILogos: function(id){
            var s = this;

            s.visibleLoader(true);
            
            $('#lbl-okfile').hide();
            s.isAtach = false;
            s.formValidator.resetForm();
			
            $.post("./?ws=Logos&act=getLogo", {
                id: id, 
                time: new Date().getTime()
            }, 
            s.onGetLogo, "json");
        },
        onGetLogo: function(data){
            var s = $;
            if(data != null && data != ""){
                $("#txttitre").val( data.txttitre );
                s.editor.setContent(data.txtdescription);
                
                s.image = {
                    name: null,
                    path: null, 
                    obj: null,
                    tSize: null,
                    size: null,
                    data: {
                        name: data.name,
                        size: data.size
                    }
                };
				
                s.iconError(false, "Image ajout&eacute;.");
                s.selectCombo( $("#cboetat"), data.cboetat );	
                s.UIEditLogos.find("#txttitre").focus().select();
                s.visibilityUILogos(true, false);
                s.visibleLoader(false);
                s.makePopup();
            } else {
                alert("Avertissement\nNe peut enregistrer vos donn\u00E9es.");
            }
        },
        makeCrop: function(image){
            var s = this;
            s.image.obj = $(image);
            s.image.obj.css({
                border:'none',
                padding:0,
                margin:0
            }).attr("id","IDImageCrop");
			
            ///var size = s.resizeToHeight(s.image.obj.attr("width"), s.image.obj.attr("height"), s.heightMin);
            s.image.tSize = {
                width:s.image.obj.attr("width"), 
                height: s.image.obj.attr("height")
            };
            //alert("width:"+ s.image.tSize.width+", height:"+ s.image.tSize.height);
			
            s.image.obj.imgAreaSelect({ 
                //minWidth: size.width,
                minHeight: s.heightMin,
                //aspectRatio: size.width + ':' + size.height,
                //onSelectChange: s.onPreview,
                onSelectEnd: s.onSelectEnd, 
                handles: true,
                parent: '#IDPhoto'
            });
			
            $('#IDPreview').empty();
            /*var ss = $('<img src="' + s.image.path+'" style="position: relative;" />');
			$('#IDPreview').append(ss).css({
				width: size.width + 'px',
				height: size.height + 'px'
			});*/
			
            s.visibleLoader(false);
            $("#IDCropArea").show();
        },
        resizeToHeight: function(rWidth, rHeight, height){
            var ratio = height / rHeight;
            var width = Math.round(rWidth * ratio);
            return {
                width: width, 
                height: height
            };
        },	
        resizeToWidth: function(rWidth, rHeight, width){
            var ratio = width / rWidth;
            var height = Math.round(rHeight * ratio);
            return {
                width: width, 
                height: height
            };
        },
        onPreview: function(img, selection){
            var image = $(img);
            $.image.tSize.width
            var scaleX = $.image.tSize.width / (selection.width || 1);
            var scaleY = $.image.tSize.height / (selection.height || 1);
		  			
            $('#IDPreview img').css({
                width: Math.round(scaleX * image.width()) + 'px',
                height: Math.round(scaleY * image.height()) + 'px',
                marginLeft: '-' + Math.round(scaleX * selection.x1) + 'px',
                marginTop: '-' + Math.round(scaleY * selection.y1) + 'px'
            });
        },
        onSelectEnd: function(img, selection){
            $.image.size = selection;
        },
        isSelectedCrop: function(){
            var s = this;
            b = false;
            if(s.image && s.image.size){
                b = true;
            }
            return b;
        },
        removeCrop: function(){
            var s = this;
            $('#IDPhoto').empty();
            s.image.obj.empty();
            s.image.obj.remove();
            $('#IDPreview').empty();
            s.visibilityUILogosCrop(false);
        },
        setCropImage: function(){
            var s = this;
            var i = this.image;
            var id = "";
            if(s.isMode == modes.Update) id = s.id;

            $.post("./?ws=Logos&act=crop", {
                x1: i.size.x1, 
                y1: i.size.y1, 
                width: i.size.width, 
                height: i.size.height, 
                name: i.name, 
                annonce: true, 
                id: id, 
                time: new Date().getTime()
            }, 
            s.onFinishedCropImage, "json");
        },
        onFinishedCropImage: function(data){
            var s = $;
            if(data != null && data != ""){
                s.image.data = data;
                s.isAtach = true;
                s.visibleLoader(false);
                s.removeCrop();
                s.iconError(false, "Image ajout&eacute;.");
            } else {
                alert("ERROR!!");
            }
        },
        saveInsertLogo: function(){
            var s = this;
            if(s.formLogos.valid()){
                //                if(s.isAtach){
                s.visibleLoader(true);
                
                var postdata = {
                    txttitre: $("#txttitre").val(), 
                    txtdescription: s.editor.getContent(), 
                    cboetat: $("#cboetat").val(), 
                    annonce: true, 
                    name: '', 
                    size: '', 
                    time: new Date().getTime()
                }
              
                if (s.isAtach) {
                    var img = s.image.data;
                    postdata.name = img.name;
                    postdata.size = img.size;
                }
                    
                $.post("./?ws=Logos&act=addLogo", postdata, 
                    function(data){
                        if(data != ""){
                            alert(data);
                            s.visibleLoader(false);
                            s.visibilityUILogos(false);
                            s.grid.trigger('reloadGrid');
                            s.popup.xpopup('hide');
                        }
                    });
            //                } else {
            //                    alert("S\u00E9lectionnez une image.");
            //                    s.iconError(true, "S&eacute;lectionnez une image");
            //                }
            }
        },
        saveUpdateLogo: function(){
            var s = this;
            if(s.formLogos.valid()){
                //                if(s.image.data){
                s.visibleLoader(true);
               
                var postdata = {
                    id: s.id,
                    txttitre: $("#txttitre").val(),
                    txtdescription: s.editor.getContent(), 
                    cboetat: $("#cboetat").val(),
                    annonce: true,
                    name: '', 
                    size: '', 
                    time: new Date().getTime()
                }
                
                if(s.image.data){
                    var data = s.image.data;
                    postdata.name = data.name; 
                    postdata.size = data.size;
                }
                
                $.post("./?ws=Logos&act=editLogo", postdata, 
                    function(data){
                        if(data != ""){
                            alert(data);
                            s.visibleLoader(false);
                            s.visibilityUILogos(false);
                            s.grid.trigger('reloadGrid');
                            s.popup.xpopup('hide');
                        // update current planche
                        //                            s.loadLogosByPart( s.cboplanches.val() );
                        }
                    });
            //                }
            //                else{
            //                    alert("S\u00E9lectionnez une image.");
            //                    s.iconError(true, "S&eacute;lectionnez une image");
            //                }
            }
        },
        removeLogo: function(ids){
            var s = this;
			
            ids = "\"" + ids + ", 0\"";
			
            if(confirm("Voulez-vous vraiment effacer le(s) logo(s)?")){
                s.visibleLoader(true);
				
                $.post("./?ws=Logos&act=removeLogo", {
                    ids: ids, 
                    annonce: true, 
                    time: new Date().getTime()
                }, 
                function(data){
                    if(data != ""){
                        alert(data);
                        s.visibleLoader(false);
                        s.grid.trigger('reloadGrid');
                    // update current planche
                    //                        s.loadLogosByPart( s.cboplanches.val() );
                    }
                });
            }
        },
        visibilityUILogos: function(visible, reset){
            var s = this;
			
            if(visible){
                //                s.UIEditLogos.show();
                if(reset) s.formLogos.reset();
                s.formValidator.resetForm();
                s.UIEditLogos.find("#txttitre").focus().select();
            //                s.UILogos.hide();
            } else {
                //                s.UIEditLogos.hide();
                //                s.UILogos.show();
                s.isMode = modes.None;
            }
        },
        visibilityUILogosCrop: function(visible){
            var s = this;

            if(visible){
                $('#IDPhoto').empty();
                s.UICrop.xpopup('show');
                s.popup.xpopup('hide');
            }
            else{
                $('#IDPhoto').empty();
                s.UICrop.xpopup('hide');
                s.popup.xpopup('show');
            }
        }
    });
	
    $.init();
});